<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>注册 - 虚拟银行系统</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="/css/main.css">
  <style>
    /* Register page specific styles */
    body {
      background-color: var(--bg-color);
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .auth-container {
      width: 100%;
      max-width: 1200px;
      height: 700px;
      display: flex;
      border-radius: var(--border-radius-lg);
      overflow: hidden;
      box-shadow: var(--modal-shadow);
    }
    
    .auth-banner {
      flex: 1;
      background-color: var(--primary-color);
      color: white;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: var(--spacing-xl);
      position: relative;
      overflow: hidden;
    }
    
    .auth-banner::before {
      content: '';
      position: absolute;
      top: -10%;
      right: -10%;
      width: 300px;
      height: 300px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .auth-banner::after {
      content: '';
      position: absolute;
      bottom: -15%;
      left: -15%;
      width: 400px;
      height: 400px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.05);
    }
    
    .auth-banner-title {
      font-size: 36px;
      font-weight: 600;
      margin-bottom: var(--spacing-md);
      z-index: 1;
    }
    
    .auth-banner-subtitle {
      font-size: 16px;
      text-align: center;
      max-width: 300px;
      margin-bottom: var(--spacing-lg);
      z-index: 1;
    }
    
    .auth-banner-features {
      margin-top: var(--spacing-lg);
      z-index: 1;
    }
    
    .auth-banner-feature {
      display: flex;
      align-items: center;
      margin-bottom: var(--spacing-md);
    }
    
    .auth-banner-feature-icon {
      margin-right: var(--spacing-md);
      font-size: 24px;
      color: var(--accent-color);
    }
    
    .auth-content {
      flex: 1;
      background-color: white;
      padding: var(--spacing-xl);
      display: flex;
      flex-direction: column;
      justify-content: center;
      overflow-y: auto;
    }
    
    .auth-header {
      text-align: center;
      margin-bottom: var(--spacing-lg);
    }
    
    .auth-title {
      font-size: 24px;
      font-weight: 600;
      color: var(--title-color);
      margin-bottom: var(--spacing-sm);
    }
    
    .auth-subtitle {
      color: var(--light-text);
    }
    
    .auth-form {
      width: 100%;
      max-width: 400px;
      margin: 0 auto;
    }
    
    .auth-footer {
      text-align: center;
      margin-top: var(--spacing-xl);
      color: var(--light-text);
    }
    
    .form-row {
      display: flex;
      gap: var(--spacing-md);
      margin-bottom: var(--spacing-md);
    }
    
    .form-row .form-group {
      flex: 1;
      margin-bottom: 0;
    }
    
    .input-with-icon {
      position: relative;
    }
    
    .input-with-icon i {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--light-text);
    }
    
    .input-with-icon input {
      padding-left: 40px;
    }
    
    .input-with-icon .input-icon-right {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: var(--light-text);
      cursor: pointer;
    }
    
    .verification-code {
      display: flex;
      gap: var(--spacing-md);
    }
    
    .verification-code input {
      flex: 1;
    }
    
    .verification-code button {
      white-space: nowrap;
    }
    
    .agreement {
      margin-top: var(--spacing-lg);
      margin-bottom: var(--spacing-lg);
    }
    
    .checkbox-container {
      display: flex;
      align-items: flex-start;
    }
    
    .custom-checkbox {
      width: 18px;
      height: 18px;
      border: 1px solid var(--border-color);
      border-radius: 3px;
      margin-right: 8px;
      margin-top: 3px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      flex-shrink: 0;
    }
    
    .custom-checkbox i {
      color: white;
      font-size: 12px;
      display: none;
    }
    
    input[type="checkbox"]:checked + .custom-checkbox {
      background-color: var(--secondary-color);
      border-color: var(--secondary-color);
    }
    
    input[type="checkbox"]:checked + .custom-checkbox i {
      display: block;
    }
    
    input[type="checkbox"] {
      display: none;
    }
    
    /* Responsive */
    @media (max-width: 991px) {
      .auth-banner {
        display: none;
      }
      
      .auth-container {
        max-width: 500px;
        height: auto;
      }
    }
    
    @media (max-width: 575px) {
      .auth-container {
        box-shadow: none;
        border-radius: 0;
      }
      
      .auth-content {
        padding: var(--spacing-lg);
      }
      
      .form-row {
        flex-direction: column;
        gap: 0;
      }
    }
  </style>
</head>
<body>
  <div class="auth-container">
    <!-- Left Banner -->
    <div class="auth-banner">
      <h1 class="auth-banner-title">虚拟银行系统</h1>
      <p class="auth-banner-subtitle">安全、便捷、专业的在线银行服务</p>
      
      <div class="auth-banner-features">
        <div class="auth-banner-feature">
          <div class="auth-banner-feature-icon">
            <i class="fas fa-shield-alt"></i>
          </div>
          <div>安全的账户管理</div>
        </div>
        <div class="auth-banner-feature">
          <div class="auth-banner-feature-icon">
            <i class="fas fa-exchange-alt"></i>
          </div>
          <div>便捷的资金转账</div>
        </div>
        <div class="auth-banner-feature">
          <div class="auth-banner-feature-icon">
            <i class="fas fa-chart-line"></i>
          </div>
          <div>丰富的理财产品</div>
        </div>
        <div class="auth-banner-feature">
          <div class="auth-banner-feature-icon">
            <i class="fas fa-hand-holding-usd"></i>
          </div>
          <div>灵活的贷款服务</div>
        </div>
      </div>
    </div>
    
    <!-- Right Register Form -->
    <div class="auth-content">
      <div class="auth-header">
        <h2 class="auth-title">创建账户</h2>
        <p class="auth-subtitle">填写以下信息完成注册</p>
      </div>
      
      <form class="auth-form" id="register-form">
        <div class="form-group">
          <label class="form-label" for="username">用户名</label>
          <div class="input-with-icon">
            <i class="fas fa-user"></i>
            <input type="text" id="username" name="username" class="form-control" placeholder="请设置用户名" required>
          </div>
          <div class="form-error" id="username-error"></div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label class="form-label" for="password">密码</label>
            <div class="input-with-icon">
              <i class="fas fa-lock"></i>
              <input type="password" id="password" name="password" class="form-control" placeholder="请设置密码" required>
              <button type="button" class="input-icon-right toggle-password">
                <i class="fas fa-eye-slash"></i>
              </button>
            </div>
            <div class="form-error" id="password-error"></div>
          </div>
          
          <div class="form-group">
            <label class="form-label" for="confirmPassword">确认密码</label>
            <div class="input-with-icon">
              <i class="fas fa-lock"></i>
              <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" placeholder="请再次输入密码" required>
            </div>
            <div class="form-error" id="confirmPassword-error"></div>
          </div>
        </div>
        
        <div class="form-group">
          <label class="form-label" for="phone">手机号码</label>
          <div class="input-with-icon">
            <i class="fas fa-mobile-alt"></i>
            <input type="tel" id="phone" name="phone" class="form-control" placeholder="请输入手机号码" required>
          </div>
          <div class="form-error" id="phone-error"></div>
        </div>
        
        <div class="form-group">
          <label class="form-label" for="validCode">验证码</label>
          <div class="verification-code">
            <input type="text" id="validCode" name="validCode" class="form-control" placeholder="请输入验证码" required>
            <button type="button" class="btn btn-outline" id="send-code-btn">获取验证码</button>
          </div>
          <div class="form-error" id="validCode-error"></div>
        </div>
        
        <div class="form-group">
          <label class="form-label" for="email">邮箱 (选填)</label>
          <div class="input-with-icon">
            <i class="fas fa-envelope"></i>
            <input type="email" id="email" name="email" class="form-control" placeholder="请输入邮箱地址">
          </div>
          <div class="form-error" id="email-error"></div>
        </div>
        
        <div class="agreement">
          <div class="checkbox-container">
            <input type="checkbox" id="agreement" name="agreement" required>
            <label for="agreement" class="custom-checkbox">
              <i class="fas fa-check"></i>
            </label>
            <label for="agreement">我已阅读并同意
              <a href="/terms.html" target="_blank">《用户协议》</a>和
              <a href="/privacy.html" target="_blank">《隐私政策》</a>
            </label>
          </div>
          <div class="form-error" id="agreement-error"></div>
        </div>
        
        <button type="submit" class="btn btn-primary btn-block">立即注册</button>
      </form>
      
      <div class="auth-footer">
        <p>已有账户? <a href="/login.html">立即登录</a></p>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="/js/utils/Utils.js"></script>
  <script src="/js/components/Toast.js"></script>
  <script src="/js/services/ApiService.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Register form elements
      const registerForm = document.getElementById('register-form');
      const usernameInput = document.getElementById('username');
      const passwordInput = document.getElementById('password');
      const confirmPasswordInput = document.getElementById('confirmPassword');
      const phoneInput = document.getElementById('phone');
      const validCodeInput = document.getElementById('validCode');
      const emailInput = document.getElementById('email');
      const agreementCheckbox = document.getElementById('agreement');
      const sendCodeBtn = document.getElementById('send-code-btn');
      
      // Error elements
      const usernameError = document.getElementById('username-error');
      const passwordError = document.getElementById('password-error');
      const confirmPasswordError = document.getElementById('confirmPassword-error');
      const phoneError = document.getElementById('phone-error');
      const validCodeError = document.getElementById('validCode-error');
      const emailError = document.getElementById('email-error');
      const agreementError = document.getElementById('agreement-error');
      
      // If user is already logged in, redirect to dashboard
      if (ApiService.isAuthenticated()) {
        window.location.href = '/index.html';
      }
      
      // Toggle password visibility
      const togglePassword = document.querySelector('.toggle-password');
      if (togglePassword) {
        togglePassword.addEventListener('click', function() {
          const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
          passwordInput.setAttribute('type', type);
          
          // Toggle icon
          const icon = this.querySelector('i');
          if (type === 'password') {
            icon.classList.replace('fa-eye', 'fa-eye-slash');
          } else {
            icon.classList.replace('fa-eye-slash', 'fa-eye');
          }
        });
      }
      
      // Send verification code
      let countdownTimer = null;
      
      sendCodeBtn.addEventListener('click', function() {
        // Validate phone number
        if (!phoneInput.value.trim()) {
          phoneError.textContent = '请输入手机号码';
          return;
        }
        
        if (!Utils.isValidPhoneNumber(phoneInput.value.trim())) {
          phoneError.textContent = '请输入有效的手机号码';
          return;
        }
        
        // Disable button and start countdown
        sendCodeBtn.disabled = true;
        let countdown = 60;
        sendCodeBtn.textContent = `${countdown}秒后重新获取`;
        
        countdownTimer = setInterval(() => {
          countdown--;
          sendCodeBtn.textContent = `${countdown}秒后重新获取`;
          
          if (countdown <= 0) {
            clearInterval(countdownTimer);
            sendCodeBtn.disabled = false;
            sendCodeBtn.textContent = '获取验证码';
          }
        }, 1000);
        
        // Call send verification code API
        fetch('/api/user/send-code', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          },
          params: {
            phone: phoneInput.value.trim()
          }
        })
        .then(response => response.json())
        .then(data => {
          if (data.code === 0) {
            Toast.success('验证码已发送，请查收');
          } else {
            Toast.error(data.message || '验证码发送失败，请稍后再试');
            
            // Reset countdown
            clearInterval(countdownTimer);
            sendCodeBtn.disabled = false;
            sendCodeBtn.textContent = '获取验证码';
          }
        })
        .catch(error => {
          console.error('Send code error:', error);
          Toast.error('验证码发送出错，请稍后再试');
          
          // Reset countdown
          clearInterval(countdownTimer);
          sendCodeBtn.disabled = false;
          sendCodeBtn.textContent = '获取验证码';
        });
      });
      
      // Form validation
      function validateForm() {
        let isValid = true;
        
        // Reset errors
        usernameError.textContent = '';
        passwordError.textContent = '';
        confirmPasswordError.textContent = '';
        phoneError.textContent = '';
        validCodeError.textContent = '';
        emailError.textContent = '';
        agreementError.textContent = '';
        
        // Validate username
        if (!usernameInput.value.trim()) {
          usernameError.textContent = '请输入用户名';
          isValid = false;
        } else if (usernameInput.value.trim().length < 4) {
          usernameError.textContent = '用户名至少需要4个字符';
          isValid = false;
        }
        
        // Validate password
        if (!passwordInput.value) {
          passwordError.textContent = '请输入密码';
          isValid = false;
        } else if (passwordInput.value.length < 6) {
          passwordError.textContent = '密码至少需要6个字符';
          isValid = false;
        }
        
        // Validate confirm password
        if (!confirmPasswordInput.value) {
          confirmPasswordError.textContent = '请确认密码';
          isValid = false;
        } else if (confirmPasswordInput.value !== passwordInput.value) {
          confirmPasswordError.textContent = '两次输入的密码不一致';
          isValid = false;
        }
        
        // Validate phone
        if (!phoneInput.value.trim()) {
          phoneError.textContent = '请输入手机号码';
          isValid = false;
        } else if (!Utils.isValidPhoneNumber(phoneInput.value.trim())) {
          phoneError.textContent = '请输入有效的手机号码';
          isValid = false;
        }
        
        // Validate verification code
        if (!validCodeInput.value.trim()) {
          validCodeError.textContent = '请输入验证码';
          isValid = false;
        }
        
        // Validate email (optional)
        if (emailInput.value.trim() && !Utils.isValidEmail(emailInput.value.trim())) {
          emailError.textContent = '请输入有效的邮箱地址';
          isValid = false;
        }
        
        // Validate agreement
        if (!agreementCheckbox.checked) {
          agreementError.textContent = '请阅读并同意用户协议和隐私政策';
          isValid = false;
        }
        
        return isValid;
      }
      
      // Form submission
      registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!validateForm()) {
          return;
        }
        
        // Show loading state
        const submitButton = registerForm.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';
        
        // Call register API
        fetch('/api/user/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            username: usernameInput.value.trim(),
            password: passwordInput.value,
            confirmPassword: confirmPasswordInput.value,
            phone: phoneInput.value.trim(),
            validCode: validCodeInput.value.trim(),
            email: emailInput.value.trim() || null
          })
        })
        .then(response => response.json())
        .then(data => {
          // Reset submit button
          submitButton.disabled = false;
          submitButton.textContent = originalText;
          
          if (data.code === 0 && data.data) {
            // Registration successful
            const { token, id, username } = data.data;
            
            // Store token
            ApiService.setAuthToken(token);
            
            // Store basic user info in local storage for quick access
            localStorage.setItem('userInfo', JSON.stringify({
              id,
              username
            }));
            
            // Show success message and redirect
            Toast.success('注册成功，即将跳转到首页');
            
            // Redirect to dashboard after a short delay
            setTimeout(() => {
              window.location.href = '/index.html';
            }, 1500);
          } else {
            // Registration failed
            Toast.error(data.message || '注册失败，请稍后再试');
          }
        })
        .catch(error => {
          // Reset submit button
          submitButton.disabled = false;
          submitButton.textContent = originalText;
          
          // Show error
          console.error('Registration error:', error);
          Toast.error('注册出错，请稍后再试');
        });
      });
    });
  </script>
</body>
</html>
